package app

import (
	"github.com/asticode/go-astilectron"
	bootstrap "github.com/asticode/go-astilectron-bootstrap"
	"go_gui_basic_binding/app/bindHandle"
	"go_gui_basic_binding/frame/appOptions"
	"go_gui_basic_binding/frame/bind"
	"go_gui_basic_binding/frame/log"
	"go_gui_basic_binding/frame/message"
)

// Constants

// Vars injected via ldflags by bundler
var (
	AppName            string
	VersionAstilectron string
	VersionElectron    string
	Debug              = false
)

type BaseStruct struct {
	Asset         bootstrap.Asset
	AssetDir      bootstrap.AssetDir
	RestoreAssets bootstrap.RestoreAssets
}
type initCallback func(a *astilectron.Astilectron, ws []*astilectron.Window)

func Run(index string, WindowOptions *astilectron.WindowOptions, baseData BaseStruct, callback ...initCallback) {
	// Parse flags
	if err := bootstrap.Run(bootstrap.Options{
		Asset:    baseData.Asset,
		AssetDir: baseData.AssetDir,
		Adapter : func(w *astilectron.Astilectron) {
			appOptions.Astilectron = w
		},
		AstilectronOptions: astilectron.Options{
			AppName:            AppName,
			AppIconDarwinPath:  "resources/icon.icns",
			AppIconDefaultPath: "resources/icon.png",
			SingleInstance:     true,
			VersionAstilectron: VersionAstilectron,
			VersionElectron:    VersionElectron,
		},
		OnWait: func(a *astilectron.Astilectron, ws []*astilectron.Window, _ *astilectron.Menu, _ *astilectron.Tray, _ *astilectron.Menu) error {
			appOptions.W = ws[0]
			bindHandle.Init()
			if Debug {
				for _, v := range ws {
					_ = v.OpenDevTools()
				}
			}
			if len(callback) > 1 {
				callback[0](a, ws)
			}
			return nil
		},
		RestoreAssets: baseData.RestoreAssets,
		Windows: []*bootstrap.Window{{
			Homepage:       index + ".html",
			MessageHandler: handleMessages,
			Options:        WindowOptions,
		}},
	}); err != nil {

	}
}

// handleMessages handles messages
func handleMessages(w *astilectron.Window, m bootstrap.MessageIn) (payload interface{}, err error) {
	log.Log("request:" + m.Name)
	switch m.Name {
	case "go_func":
		bind.Run(m.Payload)
	default:
		payload = message.MsgHandle(m)
	}
	return
}
